package com.yilin.tms.order.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.MathUtil;

import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.order.clearing.ClearingDetail;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.payment.ServicePaymentCost;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.remote.ICapitalRemote;
import com.yilin.tms.order.service.clearing.IClearingService;
import com.yilin.tms.order.service.order.ITransitService;
import com.yilin.tms.order.service.payment.ICalculationService;
import com.yilin.tms.order.service.payment.IOrderSettlementCostService;
import com.yilin.tms.order.service.payment.IServicePaymentCostService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order/repair/")
public class RepairController extends BaseController {

    @Resource
    ITransitService transitService;
    @Resource
    IClearingService clearingService;
    @Resource
    IOrderSettlementCostService settlementCostService;
    @Resource
    IServicePaymentCostService servicePaymentCostService;
    @Resource
    ICalculationService calculationService;
    @Resource
    ICapitalRemote capitalRemote;

    /**
     * 修复 订单费用问题
     * 需要手动删除所有服务费类型 service_fee_type = 1 的数据
     * */
    @PostMapping(value = "repairTransitCost")
    public ReturnData<Object> repairTransitCost(String startTime,String endTime) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (startTime==null) startTime = "2023-10-18 00:00:00";
        if (endTime==null) endTime = "2023-11-06 10:00:00";
        queryWrapper.between("clear_complete_time", DateTimeUtil.stringToDate(startTime,null),DateTimeUtil.stringToDate(endTime,null));
        List<TransitOrder> transitOrderList = transitService.list(queryWrapper);

        List<String> transitOrderIds = new ArrayList<>();

        for (TransitOrder _transitOrder : transitOrderList) {
            if (transitOrderIds.contains(_transitOrder.getId())) continue;

            OrderSettlementCost _settlementCost = settlementCostService.getOrderSettlementCostByTransitOrderId(_transitOrder.getId());
            if (_settlementCost==null) continue;
            TradeRecord tradeRecord = ParamUtil.isSuccess(capitalRemote.getTradeRecordByNo(_settlementCost.getTradeNo()));
            if (tradeRecord==null || tradeRecord.getTechnicalFee()==null) continue;
            //从这里开始从处理
            String[] orderPaymentIds = tradeRecord.getOrderPaymentIds().split(",");
            for (int i = 0; i < orderPaymentIds.length; i++) {
                String orderPaymentId = orderPaymentIds[i];
                //获取到对应的预结款单
                OrderSettlementCost settlementCost = settlementCostService.getById(orderPaymentId);
                if (settlementCost==null) continue;
                //获取到对应的清算单据
                ClearingDetail clearingDetail = clearingService.getClearingDetailByTransitOrderId(settlementCost.getTransitOrderId());
                clearingDetail.setTruckerActualTheoryCost(clearingDetail.getTruckerActualIncomeCost());
                //完全平均分配
                clearingDetail.setTechnicalFeeCost(MathUtil.average(tradeRecord.getTechnicalFee(),orderPaymentIds.length,i));
                //最后实际费用 == 理论值-技术服务非
                clearingDetail.setTruckerActualIncomeCost(MathUtil.subtract(clearingDetail.getTruckerActualTheoryCost(),clearingDetail.getTechnicalFeeCost()));
                clearingService.updateById(clearingDetail);

                settlementCost.setTechnicalFeeCost(clearingDetail.getTechnicalFeeCost());
                settlementCost.setSettlementCost(clearingDetail.getTruckerActualIncomeCost());
                settlementCostService.updateById(settlementCost);
                //最后，给运单结果赋值即可
                TransitOrder transitOrder  = transitService.getById(settlementCost.getTransitOrderId());
                transitOrder.setTruckerActualIncomeCost(clearingDetail.getTruckerActualIncomeCost());
                transitService.updateById(transitOrder);

                transitOrderIds.add(transitOrder.getId());

                //建议，删掉原来的所有服务费用单，这里重新生成
                //第一步：手动删除所有服务费类型 service_fee_type = 1 的数据
                //第二步：解开以下代码，同上一起执行即可

                //网货平台
                ServicePaymentCost servicePaymentCost1 = servicePaymentCostService.getServicePaymentCostBySourceOrderId(
                        ServicePaymentCost.ServicePlatType.whPlat,clearingDetail.getId()
                );
                if (servicePaymentCost1.getTechnicalFee()==null||servicePaymentCost1.getTechnicalFee()==0){
                    servicePaymentCost1.setOperateFee(servicePaymentCost1.getServiceCost());
                    servicePaymentCost1.setTechnicalFee(calculationService.calculatePlatTechnicalFee(servicePaymentCost1.getServicePlatId(),clearingDetail.getTechnicalFeeCost()));
                    servicePaymentCost1.setServiceCost(MathUtil.add(servicePaymentCost1.getOperateFee(),servicePaymentCost1.getTechnicalFee()));
                    servicePaymentCostService.updateById(servicePaymentCost1);
                }

                //孵化平台
                ServicePaymentCost servicePaymentCost2 = servicePaymentCostService.getServicePaymentCostBySourceOrderId(
                        ServicePaymentCost.ServicePlatType.fhPlat,clearingDetail.getId()
                );
                if (servicePaymentCost2.getTechnicalFee()==null||servicePaymentCost2.getTechnicalFee()==0){
                    servicePaymentCost2.setOperateFee(servicePaymentCost2.getServiceCost());
                    servicePaymentCost2.setTechnicalFee(calculationService.calculatePlatTechnicalFee(servicePaymentCost2.getServicePlatId(),clearingDetail.getTechnicalFeeCost()));
                    servicePaymentCost2.setServiceCost(MathUtil.add(servicePaymentCost2.getOperateFee(),servicePaymentCost2.getTechnicalFee()));
                    servicePaymentCostService.updateById(servicePaymentCost2);
                }
            }

        }

        return jsonView(true, "订单费用修复成功");
    }





}
